//
//  ViewController.m
//  PersonalOCTest
//
//  Created by zlf on 2025/4/16.
//

#import "ViewController.h"
#import "SettingsViewController.h"
#import "NewUISetViewController.h"
#import "MessageSetTViewController.h"
#import "ZLTextDemoViewController.h"
#import "DisplayStyleAlert.h"
#import "ContactManager.h"
#import "PhotoShareManager.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <objc/runtime.h> // 添加运行时框架引用
@import ContactsUI;
// 或者使用自定义 UITextView 子类
@interface NonMenuTextView : UITextView
@end

@implementation NonMenuTextView
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    return NO; // 禁用所有菜单操作
}
@end
@interface ViewController ()<UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,CNContactViewControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.yellowColor;
    
    
    [self createButtonBack:310 name:@"13800001111" action:@selector(buttonShareClicked:)];
//    [self createButtonBack:110 name:@"new" action:@selector(buttonShareClicked222:)];
//    [self createButtonBack:210 name:@"message" action:@selector(buttonShareClicked333:)];
}
- (UIButton*)createButtonBack:(CGFloat) distance name:(NSString*)name action:(SEL)action{
    // 创建第二个按钮
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button2.frame = CGRectMake(50,80 + distance,70, 39);
    [button2 setTitle:name forState:UIControlStateNormal];
    [button2 addTarget:self
                action:action
      forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];
    return button2;
}
// 按钮share的点击事件
- (void)buttonShareClicked:(UIButton *)sender {
    NSLog(@"按钮 %@ 被点击",sender.titleLabel.text);
    [self presentAddContactUIWithPhoneNumber:sender.titleLabel.text fromViewController:nil];
}

#pragma mark - 添加联系人界面
- (void)presentAddContactUIWithPhoneNumber:(NSString *)phoneNumber
                       fromViewController:(UIViewController *)presentingVC {
    CNMutableContact *contact = [[CNMutableContact alloc] init];
    CNLabeledValue *phoneNumberValue = [CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberMain
                                                                       value:[CNPhoneNumber phoneNumberWithStringValue:phoneNumber]];
    contact.phoneNumbers = @[phoneNumberValue];
    
    CNContactViewController *contactViewController = [CNContactViewController viewControllerForNewContact:contact];
    contactViewController.delegate = (id<CNContactViewControllerDelegate>)self;
    
    UINavigationController *navController = [[UINavigationController alloc]
                                             initWithRootViewController:contactViewController];
    [self presentViewController:navController animated:YES completion:nil];
}

// 实现联系人界面代理方法
#pragma mark - CNContactViewControllerDelegate
- (void)contactViewController:(CNContactViewController *)viewController
       didCompleteWithContact:(nullable CNContact *)contact {
    [viewController dismissViewControllerAnimated:YES completion:nil];
    
    if (contact) {
        NSLog( @"成功添加联系人: %@", contact.identifier);
        // 可选：触发通讯录变更处理
    }
}

- (void)testContacts {
    ContactManager *manager = [[ContactManager alloc] init];
    
    // 添加10个测试联系人
    [manager addTestContactsWithCount:2000 completion:^(NSInteger successCount, NSError * _Nullable error) {
        if (error) {
            NSLog(@"添加失败: %@", error.localizedDescription);
        } else {
            NSLog(@"成功添加 %ld 个联系人", (long)successCount);
        }
    }];
    
    // 获取所有测试联系人
//    [manager getAllTestContactsWithCompletion:^(NSArray<NSDictionary *> *testContacts, NSError * _Nullable error) {
//        if (!error) {
//            NSLog(@"找到 %lu 个测试联系人", (unsigned long)testContacts.count);
//        }
//    }];
    
    // 删除所有测试联系人
    //    [manager deleteAllTestContactsWithCompletion:^(NSInteger deletedCount, NSError * _Nullable error) {
    //        if (!error) {
    //            NSLog(@"成功删除 %ld 个测试联系人", (long)deletedCount);
    //        }
    //    }];
}
- (void)shareImageActivity {
    // 需要获取图片时
    [self loadImageWithAssetIdentifier:@"39F2B8C2-D411-45BC-A570-683FCDDCEDE9/L0/001" completion:^(UIImage *image, NSError *error) {
        if (image) {
            // 使用图片
            UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[image] applicationActivities:nil];
            activityVC.modalPresentationStyle = UIModalPresentationPopover;
            
            // Add completion handler to clean up resources
            activityVC.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable error) {
                if (error) {
                    NSLog(@"Sharing error: %@", error.localizedDescription);
                }
            };
            
            [self presentViewController:activityVC animated:YES completion:nil];
        } else {
            NSLog(@"Error: %@", error.localizedDescription);
        }
    }];
}
// 在现有代码基础上添加以下方法
- (void)loadImageWithAssetIdentifier:(NSString *)localIdentifier
                          completion:(void(^)(UIImage *_Nullable image, NSError *_Nullable error))completion
{
    PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsWithLocalIdentifiers:@[localIdentifier] options:nil];
    
    if (assets.count == 0) {
        NSError *error = [NSError errorWithDomain:@"PhotoShare" code:404
                                         userInfo:@{NSLocalizedDescriptionKey : @"未找到图片资源"}];
        completion(nil, error);
        return;
    }
    
    PHAsset *asset = assets.firstObject;
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    [[PHImageManager defaultManager] requestImageForAsset:asset
                                               targetSize:PHImageManagerMaximumSize
                                              contentMode:PHImageContentModeDefault
                                                  options:options
                                            resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        
        if (result) {
            completion(result, nil);
        } else {
            NSError *error = [NSError errorWithDomain:@"PhotoShare" code:500
                                             userInfo:@{NSLocalizedDescriptionKey : @"图片加载失败"}];
            completion(nil, error);
        }
    }];
}
- (void)setShareSystem {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.mediaTypes = @[(NSString *)kUTTypeImage];
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    PHAsset *asset = info[UIImagePickerControllerPHAsset];
    NSURL *assetURL = [NSURL URLWithString:asset.localIdentifier];//_clients    __NSCFString *    @"39F2B8C2-D411-45BC-A570-683FCDDCEDE9/L0/001"    0x0000000281a3df40
    dispatch_async(dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:nil];
        
        UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[assetURL] applicationActivities:nil];
        activityVC.modalPresentationStyle = UIModalPresentationPopover;
        
        // Add completion handler to clean up resources
        activityVC.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable error) {
            if (error) {
                NSLog(@"Sharing error: %@", error.localizedDescription);
            }
        };
        
        [self presentViewController:activityVC animated:YES completion:nil];
    });
    
}

// 适合单行文本的简单实现
- (BOOL)isTapInTextRange:(NSRange)range ofLabel:(UILabel *)label withTouchPoint:(CGPoint)point {
    // 创建文本容器
    NSString *fullText = label.text;
    NSAttributedString *attributedText = label.attributedText;
    
    // 计算文本绘制区域
    CGRect textRect = [attributedText boundingRectWithSize:label.bounds.size
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                   context:nil];
    
    // 计算实际绘制起点
    CGPoint textDrawPoint = [self textOriginWithLabel:label textSize:textRect.size];
    
    // 创建文本存储器
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedText];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:label.bounds.size];
    
    [layoutManager addTextContainer:textContainer];
    [textStorage addLayoutManager:layoutManager];
    
    // 转换坐标点
    point = CGPointMake(point.x - textDrawPoint.x, point.y - textDrawPoint.y);
    
    // 获取字符索引
    NSUInteger index = [layoutManager characterIndexForPoint:point
                                             inTextContainer:textContainer
                    fractionOfDistanceBetweenInsertionPoints:nil];
    
    return NSLocationInRange(index, range);
}

// 计算文本绘制起点
- (CGPoint)textOriginWithLabel:(UILabel *)label textSize:(CGSize)size {
    CGRect textRect = CGRectMake(0, 0, size.width, size.height);
    // 根据对齐方式调整原点
    if (label.textAlignment == NSTextAlignmentCenter) {
        textRect.origin.x = (label.bounds.size.width - size.width) / 2.0;
    } else if (label.textAlignment == NSTextAlignmentRight) {
        textRect.origin.x = label.bounds.size.width - size.width;
    }
    textRect.origin.y = (label.bounds.size.height - size.height) / 2.0;
    return textRect.origin;
}
// 同时需要实现这个代理方法
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction {
    if ([URL.scheme isEqualToString:@"action"] && [URL.host isEqualToString:@"solution"]) {
        // 处理点击事件
        [self showSolution];
        return NO;
    }
    return YES;
}
// 更新点击处理方法
- (void)handleTap:(UITapGestureRecognizer *)gesture {
    UILabel *label = (UILabel *)gesture.view;
    CGPoint location = [gesture locationInView:label];
    NSRange solutionRange = [label.text rangeOfString:@"查看解决办法"];
    
    //    if ([self isTap:location inRange:solutionRange ofLabel:label]) {
    //        [self showSolution];
    //    }
    if ([self isTapInTextRange:solutionRange ofLabel:label withTouchPoint:location]) {
        NSLog(@"跳转到解决方法页面");
    }
}

// 检测点击位置方法
// 添加在 handleTap: 方法下方
- (BOOL)isTap:(CGPoint)location inRange:(NSRange)targetRange ofLabel:(UILabel *)label {
    // 创建文本容器
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:label.frame.size];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:label.attributedText];
    
    [textStorage addLayoutManager:layoutManager];
    [layoutManager addTextContainer:textContainer];
    
    // 转换坐标系
    CGPoint textContainerOffset = CGPointMake(
                                              location.x - label.bounds.origin.x,
                                              location.y - label.bounds.origin.y
                                              );
    
    // 获取字符索引
    NSUInteger index = [layoutManager characterIndexForPoint:location
                                             inTextContainer:textContainer
                    fractionOfDistanceBetweenInsertionPoints:nil];
    
    // 判断是否在目标范围内
    return NSLocationInRange(index, targetRange);
}
- (void)showSolution {
    // 实现跳转逻辑
    NSLog(@"跳转到解决方法页面");
}
- (void)showDisplayStyleAlert {
    // 创建弹窗
    DisplayStyleAlert *alert = [[DisplayStyleAlert alloc] init];
    
    // 设置初始值
    alert.isScreenDisplayEnabled = YES; // 设置息屏显示开关初始状态
    alert.selectedDisplayMode = 0; // 设置初始显示模式为简洁
    
    // 设置确认回调
    alert.confirmBlock = ^(BOOL isScreenDisplayEnabled, NSInteger selectedMode) {
        // 处理用户选择的设置
        NSLog(@"息屏显示: %@", isScreenDisplayEnabled ? @"开启" : @"关闭");
        
        NSString *modeName;
        switch (selectedMode) {
            case 0:
                modeName = @"简洁";
                break;
            case 1:
                modeName = @"详细";
                break;
            case 2:
                modeName = @"智能折叠";
                break;
            default:
                modeName = @"未知";
                break;
        }
        NSLog(@"显示模式: %@", modeName);
        
        // 保存设置
        [[NSUserDefaults standardUserDefaults] setBool:isScreenDisplayEnabled forKey:@"ScreenDisplayEnabled"];
        [[NSUserDefaults standardUserDefaults] setInteger:selectedMode forKey:@"DisplayMode"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    };
    
    // 显示弹窗
    [alert show];
}
// 按钮share的点击事件
- (void)buttonShareClicked222:(UIButton *)sender {
    NSLog(@"按钮 share 被点击");
    NewUISetViewController *settingsVC = [[NewUISetViewController alloc] init];
    [self.navigationController pushViewController:settingsVC animated:YES];
}
// 按钮share的点击事件
- (void)buttonShareClicked333:(UIButton *)sender {
    NSLog(@"按钮 share 被点击");
    MessageSetTViewController *settingsVC = [[MessageSetTViewController alloc] init];
    [self.navigationController pushViewController:settingsVC animated:YES];
}
@end

